package ACM.crawler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;
import java.util.Vector;

import domain.Author;
import domain.Paper;

public class ACMCrawler{
	
	public static Paper extractInfoACM(Paper acmPaper) throws IOException{ // ACM PAPER PAGE EXTRACT INFO
		String inputLine=new String(); URL ACMpage = new URL(acmPaper.getDocumentUrl());
		BufferedReader in = new BufferedReader(new InputStreamReader(ACMpage.openStream(), "UTF-8"));
		Random randomGenerator = new Random();	int randomInt = randomGenerator.nextInt(8);	randomInt= (randomInt+1)*250;

		int current=0;
		try{
			Thread.sleep(randomInt);  
		}catch (InterruptedException ie){
			System.out.println(ie.getMessage());
		}
		String fixA = new String();
		while ((inputLine = in.readLine()) != null){ // parsing a paper
			if(inputLine.contains("<small>")){ //EMAIL and AFFILIANTION && inputLine.contains("University"	
				String []temp = (inputLine.split("<small>")[1]).split("</small>");
				if(temp[0].contains("Email: ")){
					String []tmp = temp[0].split("Email: ");
					String affiliation = tmp[0]; String email = tmp[1];
					affiliation = affiliation.toLowerCase();
					if(affiliation.contains("university of") && affiliation.contains(",")){
						System.out.println(affiliation);
						affiliation = affiliation.split("university of ")[1].split(",")[0];
						fixA="university of "+affiliation;
					}
					else if(temp[0].contains("university,")){
						temp[0]=temp[0].split(" university,")[0];
						if(temp[0].contains(",")){
							temp = temp[0].split(", ");
							fixA= temp[temp.length-1]+" university";
						}
					}
					else
						fixA=temp[0];
					acmPaper.getAuthors().get(current).setAffiliation(fixA);
					acmPaper.getAuthors().get(current).setEmail(email);
				}
				else{
					temp[0]= temp[0].toLowerCase();
					System.out.println("TEMP "+temp[0]);
					if(temp[0].contains("university of") && temp[0].contains(",")){
						temp[0] = temp[0].split("university of ")[1].split(",")[0];
						fixA="university of "+temp[0];
					}
					else if(temp[0].contains("university,")){
						temp[0]=temp[0].split(" university,")[0];
						if(temp[0].contains(",")){
							temp = temp[0].split(", ");
							fixA= temp[temp.length-1]+" university";
						}
					}
					else
						fixA=temp[0];
					acmPaper.getAuthors().get(current).setAffiliation(fixA);	
				}         
				current++;
			}
		}	
		in.close();
		return acmPaper;
	}
}